package com.houkunlin.wake.lan.cmd;

import com.google.common.primitives.Bytes;
import com.houkunlin.system.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HouKunLin
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Computer {
    private String mac;
    private String gateway = "255.255.255.255";
    private int port = 9;

    public Computer(final String mac) {
        this.mac = mac;
    }

    public InetAddress getGatewayAddress() {
        if (StringUtils.hasText(gateway)) {
            try {
                final String[] strings = gateway.split("\\.");
                final List<Byte> byteList = Arrays.stream(strings).map(s -> Integer.valueOf(s).byteValue()).collect(Collectors.toList());
                return InetAddress.getByAddress(Bytes.toArray(byteList));
            } catch (UnknownHostException e) {
                throw new BusinessException("网关地址错误", e);
            }
        }
        throw new BusinessException("网关地址错误");
    }

    public byte[] getMacBytes() {
        if (StringUtils.hasText(mac)) {
            try {
                final String[] strings = mac.replace("-", ":").split(":");
                final List<Byte> byteList = Arrays.stream(strings).map(s -> Integer.valueOf(s, 16).byteValue()).collect(Collectors.toList());
                return Bytes.toArray(byteList);
            } catch (Exception e) {
                throw new BusinessException("MAC 地址错误", e);
            }
        }
        throw new BusinessException("MAC 地址错误");
    }
}
